package com.yx.cloud.fragment;

import android.bluetooth.BluetoothAdapter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.iot.common.utils.LogUtils;
import com.yx.cloud.R;
import com.yx.cloud.activity.AddEquipmentActivity;
import com.yx.cloud.activity.MainActivity2;
import com.yx.cloud.adapter.AddDevice_BluetoothListAdapter;
import com.yx.cloud.base.LazyLoadFragment;
import com.yx.cloud.product.laser.tuyapublic.BluetoothScanDeviceBean;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.ToastUtil;
import com.yx.cloud.utils.WifiAdmin;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class MenuNoDeviceFragment extends LazyLoadFragment {
    private final static String TAG = "MenuNoDeviceFragment";
    public int REQUEST_CODE_ASK_PERMISSIONS = 1;
    MainActivity2 activity;
    private Button mBtnAddDevice;
    private WifiAdmin wifiAdmin;
    private BluetoothScanDeviceBean bsb;
    private List<BluetoothScanDeviceBean> leeee = new ArrayList<>();
    private List<String> mPermissionList = new ArrayList<>();
    private AddDevice_BluetoothListAdapter abla;
    private RecyclerView mBluetoothDeviceList;
    private boolean ALi = false;
    private String mTmall_userNickname;
    private boolean hasPermissionDismiss = false;
    private BluetoothAdapter mBluetoothAdapter;
    private boolean enable;
    private boolean doesItExist = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int setContentView() {
        return R.layout.menu_no_device_fragment;
    }

    @Override
    public void onPageSelect(int position) {
        super.onPageSelect(position);
    }

    @Override
    public void onPageUnselect(int position) {
        super.onPageUnselect(position);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        initView();
        initData();
        return view;
    }

    private void initView() {
        activity = (MainActivity2) getActivity();
        LogUtils.i("  MenuNoDeviceFragment======initView========= : ");
        mBtnAddDevice = findViewById(R.id.btn_addDevice);
        mBluetoothDeviceList = findViewById(R.id.bluetoothDeviceList);
    }

    private void initData() {
        LogUtils.i("  MenuNoDeviceFragment======initData========= : ");
        mBtnAddDevice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                if (EventBus.getDefault().isRegistered(getActivity())) {
                    EventBus.getDefault().unregister(getActivity());
                }
                //添加设备
                if (wifiAdmin == null) {
                    wifiAdmin = new WifiAdmin(getActivity());
                }
                String checkState = wifiAdmin.checkState(getActivity());
                if (checkState.equals("1")) {
                    //wifiManager.openWifi();
                    ToastUtil.show(getActivity(), getString(R.string.U_T_Wifi_NoOpen), Toast.LENGTH_LONG);
                    return;
                }
                Intent_utils.enterIntentMenu(getActivity(), AddEquipmentActivity.class);
                leeee.clear();
                abla.notifyDataSetChanged();
            }
        });
//        tmallBluethoothScanInitialize();
    }

   /* private void tmallBluethoothScanInitialize() {
        LogUtils.i("  tmallBluethoothScanInitialize=============== : ");
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        //天猫蓝牙扫描
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        openBluetooth();
        tmallBluethoothScan();
    }


    private void tmallBluethoothScan() {
        LogUtils.i("  tmallBluethoothScan=============== : ");
        leeee.clear();
        ALi = false;
        if (abla == null) {
            abla = new AddDevice_BluetoothListAdapter(activity, leeee);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(activity);
            mBluetoothDeviceList.setLayoutManager(linearLayoutManager);
            mBluetoothDeviceList.setAdapter(abla);
        }
        abla.notifyDataSetChanged();
        abla.setOnItemClickListener(new AddDevice_BluetoothListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                if (v.getId() == R.id.btn_startConfiguration) {
                    if (leeee.size() > 0) {
                        LocalDeviceMgr.getInstance().stopDiscovery();//天猫停⽌设备发现
                        Log.i(TAG, "点击了开始配置按钮 -------------------------》  :");
                        SharedPrefsUtil.putValue(activity, "ROBOT_SERIES", "robot_series", "bluetooth");//给配网失败后返回使用
                        BluetoothScanDeviceBean deviceBean = leeee.get(position);
                        String source = deviceBean.getSource();//区分蓝牙扫描出来的设备 是X5 基站还是其他机型的
                        if ("ali".equals(source)) {
                            AppContext.get().setRobotType("X5");
                            mTmall_userNickname = SharedPrefsUtil.getValue(activity, "TMALL_ALIGENIE_USER_INFO", "tmall_aligenie_user_info", "");
                            INXNIConstant.TMALL_USER_NICK_NAME = mTmall_userNickname;
                            //已经登录成功了，不在进行登录直接进行绑定
                            if ("".equals(mTmall_userNickname)) {
                                Intent select = new Intent(activity, BindTaobaoAccountActivity.class);
                                select.putExtra("network", "bluetooth");
                                select.putExtra("bluetoothData", deviceBean);
                                startActivity(select);
                            } else {
                                Intent intent = new Intent(activity, TmallUnbindUserActivity.class);
                                intent.putExtra("network", "bluetooth");
                                intent.putExtra("source", "X5");
                                intent.putExtra("nickname", INXNIConstant.TMALL_USER_NICK_NAME);
                                intent.putExtra("bluetoothData", deviceBean);//保存的X5蓝牙信息
                                startActivity(intent);
                            }
                        } else {
                            Product product = ProductManager.getProductById(deviceBean.getProductId());
                            String seriesName = ((SweeperProductConfig) product.getConfig()).productName;
                            AppContext.get().setRobotType(seriesName);
                            Intent select = new Intent(activity, SelectWIFIActivity.class);
                            select.putExtra("network", "bluetooth");
                            select.putExtra("source", "other");
                            select.putExtra("bluetoothData", deviceBean);
                            startActivity(select);
                        }
                    } else {
                        abla.notifyDataSetChanged();
                    }
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_TUYA_BLUETOOTH_SCAN:
                //涂鸦蓝牙扫描回调 TODO:涂鸦内部已经做了重复过滤了
                doesItExist = false;
                ScanDeviceBean bean = (ScanDeviceBean) event.getContent();
                LogUtils.d("涂鸦 event Bluetooth scan  :::::::::::::::::::::::::: " + new Gson().toJson(bean));
                Product product = ProductManager.getProductById(bean.getProductId());
                LogUtils.d(product + " : 涂鸦 event bean.getProductId()  :::::::::::::::::::::::::: " + bean.getProductId());
                if (product == null) {
                    return;
                }
                if (leeee.size() > 0) {
                    for (int i = 0; i < leeee.size(); i++) {
                        if (bean.getAddress().equals(leeee.get(i).getAddress())) {
                            doesItExist = true;
                        }
                    }
                }
                String name = ((SweeperProductConfig) product.getConfig()).productName;
                LogUtils.d("涂鸦 event name  :::::::::::::::::::::::::: " + name);
                if (Constants.FLAVOR_INXNI.equals(BuildConfig.FLAVOR)) {
                    //涂鸦蓝牙搜索时X5的机器不显示，只显示天猫精灵
                    if (product == X3S_P2P.get() || product == X3.get() || product == X1.get() || product == X3_PD35_61_P2P.get()) {
                        LogUtils.d("涂鸦 Bluetooth scan  :::::::::::::::::::::::::: " + new Gson().toJson(bean));
                        scanDataPackage("tuya", bean, null);
                        abla.notifyDataSetChanged();
                    } else if (product == X5.get()) {
                        //如果是x5的机器就存起来给配网使用 TODO:暂时没用到
                        bsb = new BluetoothScanDeviceBean();
                        bsb.setSource("tuya");
                        bsb.setMac(bean.getMac());
                        bsb.setAddress(bean.getAddress());
                        bsb.setUuid(bean.getUuid());
                        bsb.setFlag(bean.getFlag());
                        bsb.setId(bean.getId());
                        bsb.setName(bean.getName());
                        bsb.setDeviceType(bean.getDeviceType());
                        bsb.setProviderName(bean.getProviderName());
                        bsb.setProductId(bean.getProductId());
                        bsb.setConfigType(bean.getConfigType());
                        AppContext.get().x5_bluetoothdeviceList.add(bsb);
                    }
                } else if (Constants.FLAVOR_ICLEBO.equals(BuildConfig.FLAVOR)) {
                    LogUtils.d("银星 涂鸦 event name  :::::::::::::::::::::::::: " + name);
                    if (product == GD48.get() || product == G5MAX.get() || product == G20.get()) {
                        LogUtils.d("涂鸦 Bluetooth scan  :::::::::::::::::::::::::: " + new Gson().toJson(bean));
                        scanDataPackage("tuya", bean, null);
                        abla.notifyDataSetChanged();
                    }
                } else if (Constants.FLAVOR_YINXING.equals(BuildConfig.FLAVOR)) {
                    if ("ZW2X".equals(name)) {
                        scanDataPackage("tuya", bean, null);
                        abla.notifyDataSetChanged();
                    }
                }
                break;
            case Event.MESSAGE_TYPE_TMALL_BLUETOOTH_SCAN:
                //天猫精灵蓝牙扫描回调
                List<DeviceInfo> list = (List<DeviceInfo>) event.getContent();
                LogUtils.d(leeee.size() + " :添加 阿里 Bluetooth scan  :::::::::::::::::::::::::: " + list.toString());
                if (list.size() > 0) {
                    if (leeee.size() == 0) {
                        if (!ALi) {
                            for (int j = 0; j < list.size(); j++) {
                                DeviceInfo deviceInfo_j = list.get(j);
//                                Map extraDeviceInfo = deviceInfo_j.getExtraDeviceInfo();
//                                LogUtils.d("阿里 Bluetooth scan OO  " + new Gson().toJson(deviceInfo_j.getExtraDeviceInfo()));
                                scanDataPackage("ali", null, deviceInfo_j);
                            }
                            abla.notifyDataSetChanged();
                        }
                    } else {
                        for (int ii = 0; ii < list.size(); ii++) {
                            DeviceInfo info = list.get(ii);
                            String mac1 = info.mac;
                            for (int j = 0; j < leeee.size(); j++) {
                                if (mac1.equals(leeee.get(j).getMac())) {
                                    //说明已经存在了
                                    ALi = true;
                                }
                            }
                        }
                        if (!ALi) {
                            for (int iii = 0; iii < list.size(); iii++) {
                                DeviceInfo deviceInfo_iii = list.get(iii);
                                scanDataPackage("ali", null, deviceInfo_iii);
                            }
                            abla.notifyDataSetChanged();
                        }
                    }
                }
                break;
        }
    }

    private void scanDataPackage(String source, ScanDeviceBean bean, DeviceInfo deviceInfo) {
        if (source.equals("tuya")) {
            LogUtils.d("涂鸦 scanDataPackage  :::::::::::::::::::::::::: ");
            bsb = new BluetoothScanDeviceBean();
            bsb.setSource("tuya");
            bsb.setMac(bean.getMac());
            bsb.setAddress(bean.getAddress());
            bsb.setUuid(bean.getUuid());
            bsb.setFlag(bean.getFlag());
            bsb.setId(bean.getId());
            bsb.setName(bean.getName());
            bsb.setDeviceType(bean.getDeviceType());
            bsb.setProviderName(bean.getProviderName());
            bsb.setProductId(bean.getProductId());
            bsb.setConfigType(bean.getConfigType());
            leeee.add(bsb);
        } else {
            LogUtils.d("阿里 scanDataPackage  :::::::::::::::::::::::::: ");
            bsb = new BluetoothScanDeviceBean();
            bsb.setSource("ali");
            bsb.setDeviceId(deviceInfo.deviceId);
            bsb.setDeviceName(deviceInfo.deviceName);
            bsb.setMac(deviceInfo.mac);
            bsb.setProductId(deviceInfo.productId);
            bsb.setProductKey(deviceInfo.productKey);
            bsb.setUserId(deviceInfo.userId);
            Map extraDeviceInfo = deviceInfo.getExtraDeviceInfo();
            String info = getExtraDeviceInfo(extraDeviceInfo);
            bsb.setExtraDeviceInfo(info);
            leeee.add(bsb);
        }
    }

    @SuppressLint("MissingPermission")
    private void openBluetooth() {
        //TODO 这里只检测该有的权限是否都有了不进行权限申请，如果有了才进行蓝牙扫描
        if (!AppUtil.isLocServiceEnable(activity)) {//检测是否开启定位服务
            //未开启定位服务的操作
            LogUtils.i("--------------------------------未开启定位服务的操作");
            // locatePermissionsDialog("locationInformation");
        } else {
            //检测用户是否将当前应用的定位权限拒绝
            int checkResult = AppUtil.checkOp(activity, 2, AppOpsManager.OPSTR_FINE_LOCATION);//其中2代表AppOpsManager.OP_GPS，如果要判断悬浮框权限，第二个参数需换成24即AppOpsManager。OP_SYSTEM_ALERT_WINDOW及，第三个参数需要换成AppOpsManager.OPSTR_SYSTEM_ALERT_WINDOW
            int permission2 = ActivityCompat.checkSelfPermission(activity, Manifest.permission.BLUETOOTH_SCAN);//蓝牙扫描或WIFI扫描时需要的附近设备权限
            if (AppOpsManagerCompat.MODE_IGNORED == checkResult || permission2 != PackageManager.PERMISSION_GRANTED) {
                //未开启定位权限或者被拒绝的操作
                LogUtils.i("--------------------------------未开启GPS服务的操作");
                // locatePermissionsDialog("GPS");
            } else {
                int blu_switch = ActivityCompat.checkSelfPermission(activity, Manifest.permission.BLUETOOTH_CONNECT);
                if (blu_switch != PackageManager.PERMISSION_GRANTED) {
                    LogUtils.i("--------------------------------未开启蓝牙");
                } else {
                    //所以权限都有了
                    LogUtils.i("--------------------------------所以权限都有了");
                    AppContext.getService().tuyaStopLeScan();//涂鸦停止扫描
                    AppContext.getService().tuyaBluetoothScan();//涂鸦 开始蓝牙扫描
                    if (Constants.FLAVOR_INXNI.equals(BuildConfig.FLAVOR)) {
                        // LocalDeviceMgr.getInstance().stopDiscovery();//天猫停⽌设备发现
                        AliGenieSdk.tmallBluetoothScan(activity);//阿里 开始蓝牙扫描
                    }
                }
            }
        }
    }*/

    private String getExtraDeviceInfo(Map extraDeviceInfo) {
        String json = new Gson().toJson(extraDeviceInfo);
        JSONObject jsonObject = null;
        String netConfigFlag = null;
        try {
            jsonObject = new JSONObject(json);
            JSONObject object = jsonObject.getJSONObject("ble_discovered_device");
            netConfigFlag = object.getString("netConfigFlag");
            // if ("iLHk".equals(netConfigFlag)) {
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return netConfigFlag;
    }
}
